import {
  Badge,
  Button,
  Card,
  Col,
  DatePicker,
  Divider,
  Dropdown,
  Form,
  Icon,
  Input,
  InputNumber,
  Menu,
  Row,
  Select,
  message,
  Popconfirm,
  Radio,
} from 'antd';
import React, { Component, Fragment } from 'react';

import { Dispatch } from 'redux';
import { FormComponentProps } from 'antd/es/form';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { SorterResult } from 'antd/es/table';
import { connect } from 'dva';
import moment from 'moment';
import { StateType } from './model';
import StandardTable, { StandardTableColumnProps } from './components/StandardTable';
import { TableListItem, TableListPagination, TableListParams } from './data.d';

import styles from './style.less';
import CreateForm from './components/CreateForm';
import router from 'umi/router';

const R = require('ramda');
const FormItem = Form.Item;
const { Option } = Select;
const RadioGroup = Radio.Group;

const getValue = (obj: { [x: string]: string[] }) =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

interface TableListProps extends FormComponentProps {
  modalVisible: boolean;
  dispatch: Dispatch<any>;
  loading: boolean;
  credit: StateType;
}

interface TableListState {
  expandForm: boolean;
  selectedRows: TableListItem[];
  formValues: { [key: string]: string };
}

/* eslint react/no-multi-comp:0 */
@connect(
  ({
    credit,
    loading,
    global,
  }: {
    credit: StateType;
    global: StateType;
    loading: {
      models: {
        [key: string]: boolean;
      };
    };
  }) => ({
    credit,
    global,
    loading: loading.models.credit,
  }),
)
class TableList extends Component<TableListProps, TableListState> {
  state: TableListState = {
    modalVisible: false,
    expandForm: false,
    selectedRows: [],
    formValues: {},
  };

  columns: StandardTableColumnProps[] = [
    {
      title: '申请单号',
      dataIndex: 'id',
      render: record => {
        return 'ZBT-WS-CREDIT-' + record;
      },
    },
    {
      title: '联系人手机号',
      dataIndex: 'mobile',
    },
    {
      title: '联系人邮箱',
      dataIndex: 'email',
    },
    {
      title: '类型',
      dataIndex: 'serviceType',
      render: record => {
        if (record == '8') {
          return '审单';
        } else if (record == '9') {
          return '制单';
        } else return '审单制单';
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: record => {
        if (record == '1') {
          return '待支付';
        } else if (record == '2') {
          return '待审核';
        } else if (record == '3') {
          return '去制单';
        } else if (record == '4') {
          return '制单中';
        } else if (record == '5') {
          return '单证下载';
        } else return '状态未知';
      },
    },
    {
      title: '申请时间',
      dataIndex: 'createtime',
    },
    {
      title: '操作',
      key: 'key_oprator',
      render: record => {
        let split = <div className="ant-divider" />;
        let unapprovalfileDown = null;
        if (!R.isNil(record.unapprovalfile) && !R.isEmpty(record.unapprovalfile)) {
          unapprovalfileDown = (
            <span>
              <a
                target="_blank"
                href={PORTAL_PATH + '/api/file/download?filename=' + record.unapprovalfile}
              >
                原单证下载
              </a>
            </span>
          );
        }

        let approvedfileDown = null;
        if (!R.isNil(record.approvedfile) && !R.isEmpty(record.approvedfile)) {
          approvedfileDown = (
            <span>
              <a
                target="_blank"
                href={PORTAL_PATH + '/api/file/download?filename=' + record.approvedfile}
              >
                已审单证下载
              </a>
            </span>
          );
        }

        let buildFile = null;
        if (!R.isNil(record.buildFile) && !R.isEmpty(record.buildFile)) {
          buildFile = (
            <span>
              <a
                target="_blank"
                href={PORTAL_PATH + '/api/file/download?filename=' + record.buildFile}
              >
                已审单证下载
              </a>
            </span>
          );
        }

        let payUrl = null;
        if (record.status == '1') {
          payUrl = (
            <span>
              <a target="_blank" onClick={this.handleGetGoods.bind(this, record)}>
                支付
              </a>
            </span>
          );
        }

        let buildReceipts = null;
        if (record.status == '3') {
          payUrl = (
            <span>
              <a target="_blank" onClick={this.handleBuildReceipts.bind(this, record)}>
                制单
              </a>
            </span>
          );
        }
        return (
          <span>
            {payUrl}
            {R.isNil(payUrl) ? '' : split}
            {unapprovalfileDown}
            {R.isNil(unapprovalfileDown) ? '' : split}
            {approvedfileDown}
            {R.isNil(approvedfileDown) ? '' : split}
            {buildFile}
          </span>
        );
      },
    },
  ];

  componentDidMount() {
    const { dispatch } = this.props;

    dispatch({
      type: 'credit/queryReceipts',
      payload: {
        type: 'A',
        page: 1,
        size: 10,
      },
    });
  }

  handleGetGoods = record => {
    this.props.dispatch({
      type: 'credit/getGoods',
      payload: {
        type:
          R.isNil(record.serviceType) || R.isEmpty(record.serviceType) ? '2' : record.serviceType,
        page: 1,
        size: 10,
        onSuccess: data => {
          if (!R.isNil(data) && !R.isEmpty(data)) {
            router.push(
              '/pay/payConfirm?goodsId=' +
                data[0].id +
                '&entityid=' +
                record.id +
                '&bussinesstype=' +
                record.serviceType +
                '&extra=',
            );
          }
        },
      },
    });
  };

  //制单
  handleBuildReceipts = record => {
    this.props.dispatch({
      type: 'credit/buildReceipts',
      payload: {
        id: record.id,
        status: '4',
        onSuccess: () => {
          const { dispatch, form } = this.props;
          let type = form.getFieldValue('type');
          this.props.dispatch({
            type: 'credit/queryReceipts',
            payload: {
              type: type,
              page: 1,
              size: 10,
            },
          });
        },
      },
    });
  };

  handleStandardTableChange = (
    pagination: Partial<TableListPagination>,
    filtersArg: Record<keyof TableListItem, string[]>,
    sorter: SorterResult<TableListItem>,
  ) => {
    const { dispatch, global } = this.props;
    const { userInfo } = global;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params: Partial<TableListParams> = {
      page: pagination.current,
      size: pagination.pageSize,
      ...formValues,
      ...filters,
    };

    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }
    params.type = 'A';

    dispatch({
      type: 'credit/queryReceipts',
      payload: params,
    });
  };

  handleSelectRows = (rows: TableListItem[]) => {
    this.setState({
      selectedRows: rows,
    });
  };

  handleSearch = (e: React.FormEvent) => {
    e.preventDefault();
    const { dispatch, form, global } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = {
        ...fieldsValue,
      };

      this.setState({
        formValues: values,
      });

      dispatch({
        type: 'credit/queryReceipts',
        payload: values,
      });
    });
  };

  refreshList = props => {
    let from = props.formQuery;
    props.dispatch({
      type: 'credit/queryReceipts',
      payload: {
        type: from.getFieldValue('type'),
        page: 1,
        size: 10,
      },
    });
  };

  handleModalVisible = (flag?: boolean) => {
    this.setState({
      modalVisible: !!flag,
    });

    if (this.createForm) this.createForm.handleOpen();
  };

  handleAdd = (fields: any) => {
    const { dispatch, form } = this.props;
    fields.status = '1';
    let type = form.getFieldValue('type');
    dispatch({
      type: 'credit/apply',
      payload: {
        ...fields,
        onSuccess: () => {
          dispatch({
            type: 'credit/queryReceipts',
            payload: {
              type: type,
              page: 1,
              size: 10,
            },
          });
        },
      },
    });
    this.handleModalVisible();
  };

  renderSimpleForm() {
    const { form } = this.props;
    const { getFieldDecorator } = form;
    return (
      <Form onSubmit={this.handleSearch.bind(this)} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label={'状态'}>
              {getFieldDecorator('type', {
                initialValue: 'A',
              })(
                <RadioGroup>
                  <Radio value="A">已申请</Radio>
                  <Radio value="C">已审单</Radio>
                  <Radio value="F">已制单</Radio>
                </RadioGroup>,
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={14}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button
                style={{ marginLeft: 8 }}
                icon="plus"
                onClick={this.handleModalVisible.bind(this, true)}
              >
                立即申请
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    return this.renderSimpleForm();
  }

  render() {
    const {
      credit: { data },
      loading,
    } = this.props;

    const { selectedRows, modalVisible } = this.state;
    const parentMethods = {
      handleAdd: this.handleAdd,
      handleModalVisible: this.handleModalVisible,
    };

    return (
      <PageHeaderWrapper
        content={
          <div>
            <div>
              <b>产品说明</b>
              <br />
              1、信用证专家帮助您解读信用证的每一个条款，让您清晰了解交易条件；
              <br />
              2、您可点击下方按钮上传信用证草稿件；
              <br />
              3、在提交成功后24小时内，您的专属客服将联系您；
              <br />
              4、信用证审核结果和交单资料请关注您的邮箱和个人中心。
              <br />
            </div>
          </div>
        }
      >
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <div className={styles.tableListOperator}></div>
            <StandardTable
              selectedRows={selectedRows}
              loading={loading}
              data={data}
              columns={this.columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
        <CreateForm
          wrappedComponentRef={inst => (this.createForm = inst)}
          {...parentMethods}
          refreshList={this.refreshList}
          formQuery={this.props.form}
          dispatch={this.props.dispatch}
          modalVisible={modalVisible}
        />
      </PageHeaderWrapper>
    );
  }
}

export default Form.create<TableListProps>()(TableList);
